"""
认证相关视图模块
"""
import json
from datetime import datetime

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from utills.code_utils import generate_code, get_email_config, build_email_html
from utills.api_response import api_response
from utills.send_mail import send_email


@csrf_exempt
def sendCode(request):
    """
    发送验证码接口
    POST参数:
    {
        "data": {
            "email": "用户邮箱",
            "type": "验证码类型 (register/findPassword)"
        }
    }
    """
    if request.method != 'POST':
        return api_response(False, "仅支持POST请求", 405)

    try:
        # 解析请求数据
        request_data = json.loads(request.body)
        data = request_data.get('data', {})
        email = data.get('email')
        code_type = data.get('type')
    except json.JSONDecodeError:
        return api_response(False, "无效的JSON格式", 400)
    except AttributeError:
        return api_response(False, "参数格式错误", 400)

    # 参数校验
    if not email or not code_type:
        return api_response(False, "缺少必要参数", 400)

    if code_type not in ('register', 'findPassword'):
        return api_response(False, "无效的验证码类型", 400)

    try:
        # 获取验证码和邮件配置
        code = generate_code(request, code_type)
        title, base_message = get_email_config(code_type)

        # 构造邮件内容
        html_content = build_email_html(base_message, code)

        # 发送邮件
        send_result = send_email(email, title, html_content)

        return api_response(send_result, "发送成功" if send_result else "发送失败",
                            200 if send_result else 500)

    except Exception as e:
        # 记录错误日志
        # logger.error(f"验证码发送异常: {str(e)}")
        return api_response(False, "服务器内部错误", 500)

def verify_code(request, code_type, user_code):
    """验证码校验函数"""
    stored_code = request.session.get(f"{code_type}code")
    expiry_time = request.session.get(f"{code_type}code_expiry", 0)
    return stored_code == user_code and expiry_time > datetime.now().timestamp()